/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution
{
public:
    Node *connect(Node *root)
    {
        Node *nextLayerStart = nullptr;
        Node *nextLayerCur = nullptr;
        Node *cur = root;
        while (cur != nullptr)
        {
            if (cur->left != nullptr)
            {
                if (nextLayerStart == nullptr)
                {
                    nextLayerCur = nextLayerStart = cur->left;
                }
                else
                {
                    nextLayerCur->next = cur->left;
                    nextLayerCur = nextLayerCur->next;
                }
            }
            if (cur->right != nullptr)
            {
                if (nextLayerStart == nullptr)
                {
                    nextLayerCur = nextLayerStart = cur->right;
                }
                else
                {
                    nextLayerCur->next = cur->right;
                    nextLayerCur = nextLayerCur->next;
                }
            }
            cur = cur->next;
        }
        if (nextLayerStart != nullptr)
        {
            connect(nextLayerStart);
        }
        return root;
    }
};